$(document).ready(function(){

	// jQuery UI specific styles
	$('input[name=supportcase-date]').datepicker();
	$('input:checkbox').click(function(){
		$(this).parent().parent().toggleClass('ui-state-highlight');
	});
	
	// Uploadify's options
	$('#supportcase-file-upload').uploadify({
		'uploader'  : 'inc/uploadify.swf',
		'script'    : 'process/upload_docs.php',
		'cancelImg' : 'css/img/cancel.png',
		'buttonImg'	: 'css/img/folder_add.png',
		'folder'    : 'data/docs',
		'auto'      : false,
		'multi'		: true,
		'wmode'		: 'transparent',
		'height'	: '16',
		'scriptData': { 'otype':'supportcase', 'id':$('input[name=supportcase-supportcaseId]').val() },
		'onAllComplete'	: function(event,data){
			location.reload();
		}
	});
	
	// Case: deleting a supportcase's document
	$('a.delete-doc').click(function(){
		var e = $(this);
		$.ajax({
			type:	'POST',
			url:	'process/document_delete.php',
			data:	'id='+e.attr('href'),
			success: function(msg){
				if (msg != 'OK')
					alert(msg);
				else
					e.parent().parent().remove();
			}
		});
		return false;
	});

	// Case: seeing a supportcase's details
	$('a#details').click(function(){
		
		// Checking if we have a supportcase selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner un élément !');
			return false;
		}
		
		// Redirecting user to the supportcase
		$(this).attr('href', 'supportcases.php?id='+checked.first().val()+'&operation=edit');
		return true;
	});
	
	// Case: deleting a supportcase batch
	$('a#delete').click(function(){
		
		// Checking rights
		if (check_credentials('supportcase_delete') != 'yes'){
			alert('Vous n\'avez pas le droit d\'effectuer cette opération !');
			return false;
		}
		
		// Checking if we have at least one supportcase selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner au moins un élément !');
			return false;
		}
		
		// AJAXing deletion
		if (confirm('Êtes-vous sûr de vouloir supprimer '+checked.length+' élément(s) ?')) {
			var total = checked.length;
			showLoading();
			checked.each(function(){
				$.ajax({
					type:	'POST',
					url:	'process/supportcase_delete.php',
					data:	'id='+$(this).val(),
					success: function(msg){
						if (msg != 'OK')
							alert(msg);
						else
							checked.parent().parent().remove();
						addLoading(100/total);
						closeLoading();
					}
				});
			});
		}
		return false;
	});
	
	// Case: editing supportcase's contact
	$('input[name=supportcase-contact]').click(function(){
		var e = $(this);
		e.addClass('loading');
		$.ajax({
			type:	'POST',
			url:	'ajax/load_contacts.php',
			data:	'id='+$('input[name=supportcase-contactId]').val(),
			success: function(msg) {
				var select = $('div#select_contact');
				e.removeClass('loading');
				select.html(msg);
				select.dialog({
					resizable: true,
					height: 500,
					width: 500,
					modal: true,
					buttons: {
						'Sélectionner': function(){
							var checked = $('input:radio:checked');
							if (checked.length <= 0) {
								$('input[name=supportcase-contact]').val('');
								$('input[name=supportcase-contactId]').val('');
							} else {
								$('input[name=supportcase-contact]').val($('span#contact-'+checked.first().val()).html());
								$('input[name=supportcase-contactId]').val(checked.first().val());
							}
							$(this).dialog('close');
						},
						'Annuler': function(){
							$(this).dialog('close');
						}
					}
				});
			}
		});
	});
	
	// Case: editing supportcase's owner
	$('input[name=supportcase-owner]').click(function(){
		var e = $(this);
		e.addClass('loading');
		$.ajax({
			type:	'POST',
			url:	'ajax/load_crmusers.php',
			data:	'id='+$('input[name=supportcase-ownerId]').val(),
			success: function(msg) {
				var select = $('div#select_crmuser');
				e.removeClass('loading');
				select.html(msg);
				select.dialog({
					resizable: true,
					height: 500,
					width: 500,
					modal: true,
					buttons: {
						'Sélectionner': function(){
							var checked = $('input:radio:checked');
							if (checked.length <= 0) {
								$('input[name=supportcase-owner]').val('');
								$('input[name=supportcase-ownerId]').val('');
							} else {
								$('input[name=supportcase-owner]').val($('span#crmuser-'+checked.first().val()).html());
								$('input[name=supportcase-ownerId]').val(checked.first().val());
							}
							$(this).dialog('close');
						},
						'Annuler': function(){
							$(this).dialog('close');
						}
					}
				});
			}
		});
	});
	
	// Case: submitting a new (or edited) supportcase
	$('a#form-supportcase').click(function(){
		
		// Getting inputs
		var operation = $('input[name=supportcase-operation]'),
			id = $('input[name=supportcase-supportcaseId]'),
			state = $('select[name=supportcase-status]'),
			progress = $('select[name=supportcase-progress]'),
			priority = $('select[name=supportcase-priority]'),
			title = $('input[name=supportcase-title]'),
			contact = $('input[name=supportcase-contactId]'),
			owner = $('input[name=supportcase-ownerId]'),
			content = $('textarea[name=supportcase-content]'),
			date = $('input[name=supportcase-date]'),
			hour = $('input[name=supportcase-hour]'),
			allFields = $([]).add(title).add(contact).add(owner).add(date).add(hour);
		
		// Checking rights
		if (check_credentials('supportcase_'+operation.val()) != 'yes'){
			alert('Vous n\'avez pas le droit d\'effectuer cette opération !');
			return false;
		}
		
		// Checking form validity
		allFields.removeClass('ui-state-error');
		var valid = true;
		valid = valid && check_length(title, 'Sujet', 1, 255);
		valid = valid && check_length(contact, 'Contact', 1, 10);
		valid = valid && check_length(owner, 'Propriétaire', 1, 10);
		valid = valid && check_length(date, 'Date', 1, 10);
		valid = valid && check_length(hour, 'Heure', 1, 10);
		valid = valid && check_regexp(date, rexp_date, 'Format de date : jj/mm/aaaa');
		valid = valid && check_regexp(hour, rexp_hour, 'Format d\'heure : mm:hh');
		
		// We have errors
		if (!valid)
			return false;

		// No error: AJAX processing
		showLoading();
		$.ajax({
			type:	'POST',
			url:	'process/supportcase_'+operation.val()+'.php',
			data:	'id='+id.val()+'&status='+state.val()+'&progress='+progress.val()+'&priority='+priority.val()+'&title='+title.val()+'&contact='+contact.val()+'&owner='+owner.val()+'&content='+htmlEncode(content.val())+'&date='+date.val()+'&hour='+hour.val(),
			success: function(msg){
				addLoading(100);
				history.back();
			}
		});
		return false;
	});
	
	// Case: seeing an update's details
	$('a#details-update').click(function(){
		
		// Checking if we have an update selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner un élément !');
			return false;
		}
		
		// Redirecting user to the update
		$(this).attr('href', 'updates.php?id='+checked.first().val()+'&operation=edit');
		return true;
	});
	
	// Case: deleting a update batch
	$('a#delete-update').click(function(){
		
		// Checking rights
		if (check_credentials('update_delete') != 'yes'){
			alert('Vous n\'avez pas le droit d\'effectuer cette opération !');
			return false;
		}
		
		// Checking if we have at least one update selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner au moins un élément !');
			return false;
		}
		
		// AJAXing deletion
		if (confirm('Êtes-vous sûr de vouloir supprimer '+checked.length+' élément(s) ?')) {
			var total = checked.length;
			showLoading();
			checked.each(function(){
				$.ajax({
					type:	'POST',
					url:	'process/update_delete.php',
					data:	'id='+$(this).val(),
					success: function(msg){
						if (msg != 'OK')
							alert(msg);
						else
							checked.parent().parent().remove();
						addLoading(100/total);
						closeLoading();
					}
				});
			});
		}
		return false;
	});
});